package com.gitee.linmt.realm;

import com.gitee.linmt.entity.Permission;
import com.gitee.linmt.entity.Role;
import com.gitee.linmt.entity.UserInfo;
import com.gitee.linmt.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

/**
 * @author linmt
 */
@Slf4j
@Component
public class DatabaseRealm extends AuthorizingRealm {

    private final UserInfoService userInfoService;

    public DatabaseRealm(UserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("权限配置：DatabaseRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        UserInfo userInfo = (UserInfo) principalCollection.getPrimaryPrincipal();
        for (Role role : userInfo.getRoleList()) {
            authorizationInfo.addRole(role.getRole());
            for (Permission p : role.getPermissions()) {
                authorizationInfo.addStringPermission(p.getPermission());
            }
        }
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("登陆认证：DatabaseRealm.doGetAuthenticationInfo()");
        // 获取用户的输入的账号.
        String username = (String) authenticationToken.getPrincipal();
        // 通过 username 从数据库中查找 UserInfo 对象
        // 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        UserInfo userInfo = userInfoService.findByUsername(username);
        log.info("登陆人信息：{}", userInfo);
        if (userInfo == null) {
            // 实际项目中，登录人不存在时要抛出与之相对应的异常
            return null;
        }
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                userInfo,
                userInfo.getPassword(),
                getName()
        );
        simpleAuthenticationInfo.setCredentialsSalt(ByteSource.Util.bytes(userInfo.getSalt()));
        return simpleAuthenticationInfo;
    }
}
